<script setup>
import router from '@/router';
import {ref} from 'vue';
import {exportReportToWord} from "@/plugins/exportWord.js";
import {deleteBatch, getAllBatches, getBatchDetail} from "@/api/uploadRecord.js";
import {ElMessage, ElMessageBox} from "element-plus";

let items = ref([]);
const level = ref('');
const init = async () => {
  const res = await getAllBatches();
  items.value = res.data;
  for (let item of items.value) {
    if (item.passRate > 90) {
      item.finalLevel = '优秀';
    } else if (item.passRate > 70) {
      item.finalLevel = '良好';
    } else if (item.passRate > 50) {
      item.finalLevel = '中等';
    } else {
      item.finalLevel = '劣质';
    }
  }
};
init();

const downloadFile = async (event, itemId) => {
  event.stopPropagation();
  try {
    const res = await getBatchDetail(itemId);
    // 根据实际API响应结构调整下面的数据访问
    await exportReportToWord(res.data, '报告' + itemId);
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error('下载报告失败');
  }
};

const deleteItem = async (event, itemId) => {
  event.stopPropagation();

  // 弹窗确认删除
  try {
    await ElMessageBox.confirm(
        '确定要删除这条检测记录吗？此操作不可恢复。',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 用户确认删除后执行删除操作
    await deleteBatch(itemId);
    await init();
    ElMessage.success('删除成功');
  } catch (error) {
    // 用户取消删除或删除失败
    if (error === 'cancel') {
      // 用户取消操作，无需提示
      return;
    }
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

const navigationToDetail = (itemId) => {
  router.push({name: 'detail', params: {id: itemId}});
}
</script>

<template>
  <div class="container">
    <div class="item" v-for="item in items" :key="item.id" @click="navigationToDetail(item.id)">
      <div class="item-header">
        <h3>{{ $t("history-content1") }} #{{ item.id }}</h3>
        <span class="date">{{ item.completedAt }}</span>
        <span class="delete" @click="deleteItem($event, item.id)"> × </span>
      </div>

      <div class="data-grid">
        <div class="data-item">
          <label>{{ $t("history-content2") }}</label>
          <span class="value">{{ item.imageCount }}</span>
        </div>
        <div class="data-item">
          <label>{{ $t("history-content3") }}</label>
          <span class="value error">{{ item.totalDefects }}</span>
        </div>
        <div class="data-item">
          <label>{{ $t("history-content4") }}</label>
          <span class="value" :class="{
            'excellent-rate': parseFloat(item.passRate) >= 90,
            'good-rate': parseFloat(item.passRate) >= 80 && parseFloat(item.passRate) < 90,
            'medium-rate': parseFloat(item.passRate) >= 60 && parseFloat(item.passRate) < 80,
            'low-rate': parseFloat(item.passRate) < 60
          }">{{ item.passRate }}</span>
        </div>
        <div class="data-item">
          <label>{{ $t("history-content5") }}</label>
          <span class="value">{{ item.qualityScore }}</span>
        </div>
        <div class="data-item full-width">
          <label>{{ $t("history-content6") }}</label>
          <span class="value level-tag" :class="{
            'excellent': item.finalLevel === '优秀',
            'good': item.finalLevel === '良好',
            'medium': item.finalLevel === '中等',
            'poor': item.finalLevel === '劣质'
          }">{{ item.finalLevel }}</span>
        </div>
      </div>

      <button class="download-btn" @click="downloadFile($event ,item.id)">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
          <path
              d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/>
          <path
              d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/>
        </svg>
        {{ $t("upload-tip6") }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  padding: 20px 10vw;
  width: 100%;
  box-sizing: border-box;
}

.item {
  background: var(--history-card-bg);
  border: 1px solid var(--history-border);
  border-radius: 12px;
  box-shadow: var(--history-shadow);
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  transition: all 0.3s ease;
}

.item:hover {
  transform: translateY(-5px);
  box-shadow: var(--history-shadow-hover);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border-bottom: 1px solid var(--history-border);
  padding-bottom: 16px;
}

.item-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: var(--history-text-primary);
  font-weight: 600;
}

.delete {
  cursor: pointer;
  color: var(--txcolor);
}

.date {
  font-size: 0.9rem;
  color: var(--history-text-secondary);
  background: var(--card-bg);
  padding: 6px 12px;
  border-radius: 20px;
  font-weight: 500;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.data-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.data-item.full-width {
  grid-column: span 2;
}

.data-item label {
  font-size: 0.85rem;
  color: var(--history-text-secondary);
  font-weight: 500;
}

.data-item .value {
  font-weight: 600;
  color: var(--history-text-primary);
  font-size: 1.1rem;
}

.data-item .value.error {
  color: var(--history-rate-low);
}

.data-item .value.excellent-rate {
  color: var(--history-rate-excellent);
}

.data-item .value.good-rate {
  color: var(--history-rate-good);
}

.data-item .value.medium-rate {
  color: var(--history-rate-medium);
}

.data-item .value.low-rate {
  color: var(--history-rate-low);
}

.level-tag {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 600;
  width: fit-content;
}

.level-tag.excellent {
  background-color: var(--history-level-excellent);
  color: var(--history-rate-excellent);
}

.level-tag.good {
  background-color: var(--history-level-good);
  color: var(--history-rate-good);
}

.level-tag.medium {
  background-color: var(--history-level-medium);
  color: var(--history-rate-medium);
}

.level-tag.poor {
  background-color: var(--history-level-poor);
  color: var(--history-rate-low);
}

.download-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: var(--history-accent);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s ease;
  margin-top: auto;
  font-size: 0.95rem;
}

.download-btn:hover {
  background: var(--history-accent-hover);
}

@media screen and (max-width: 768px) {
  .container {
    grid-template-columns: 1fr;
    padding: 16px;
    gap: 20px;
  }

  .item {
    padding: 20px;
  }

  .data-grid {
    grid-template-columns: 1fr;
  }

  .data-item.full-width {
    grid-column: span 1;
  }

  .item-header {
    flex-direction: column;
    gap: 12px;
  }
}

@media screen and (max-width: 480px) {
  .container {
    padding: 12px;
  }

  .item {
    padding: 16px;
  }

  .download-btn {
    width: 100%;
  }
}
</style>
